package service

import (
	"context"
	"errors"
	"pmservice/db"
	"pmservice/graph/model"
)

func (s *Service) FacNew(ctx context.Context, input model.FacNew) (*model.Facility, error) {
	hos := db.HospitalGet(s.Orm.DB, input.Hosuid)
	if hos == nil {
		return nil, errors.New("hos not found")
	}
	d, err := db.FacNew(s.Orm.DB, &input)
	if err != nil {
		return nil, errors.New("fac create failed")
	}
	return s.FacGet(ctx, d.UID, "")
}

func (s *Service) FacSave(ctx context.Context, uid string, input model.FacEdit) (bool, error) {
	fac := db.FacGet(s.Orm.DB, uid)
	if fac == nil {
		return false, errors.New("fac not found")
	}
	return db.FacSave(s.Orm.DB, fac.Hospital, uid, &input), nil
}

func (s *Service) FacDelete(ctx context.Context, uid string) (bool, error) {
	return db.FacDel(s.Orm.DB, uid), nil
}

func (s *Service) FacGetCompositeData(ctx context.Context, d *db.Fac, prefix string) (*model.Facility, error) {
	ret := d.ToGQL()
	if HasField(ctx, PrefixJoin(prefix, "hospital")) {
		ret.Hospital, _ = s.HospitalGet(ctx, d.Hospital, PrefixJoin(prefix, "hospital"))
	}

	if HasField(ctx, PrefixJoin(prefix, "pocs")) {
		pocs, _ := s.PocSearch(ctx, model.PocSearchCond{
			Hosuid: d.Hospital,
			Facuid: &d.UID,
		}, PrefixJoin(prefix, "pocs"))
		ret.Pocs = pocs.Results
	}

	return ret, nil
}

func (s *Service) FacGet(ctx context.Context, uid string, prefix string) (*model.Facility, error) {
	d := db.FacGet(s.Orm.DB, uid)
	if d == nil {
		return nil, errors.New("fac not found")
	}

	return s.FacGetCompositeData(ctx, d, prefix)
}

func (s *Service) FacSearch(ctx context.Context, cond model.FacSearchCond, prefix string) (*model.FacSearchResult, error) {
	facs, total := db.FacSearch(s.Orm.DB, cond)
	ret := model.FacSearchResult{
		Results: make([]*model.Facility, 0),
		Total:   int(total),
	}

	for _, f := range facs {
		fac, _ := s.FacGetCompositeData(ctx, f, prefix)
		if fac != nil {
			ret.Results = append(ret.Results, fac)
		}
	}

	return &ret, nil
}
